package com.ruoyi.hr.controller;


import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.hr.domain.HrBgfile;
import com.ruoyi.hr.domain.HrResume;
import com.ruoyi.hr.service.IHrResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/hr/resumefile")
public class HrFileController {

	@Autowired
	private IHrResumeService hrResumeService;

	/**
	 * 简历下载, 针对本地, 要是oss的根本就不需要这个下载操作
	 * 仅供内部拼接然后交给前端请求
	 */
	@GetMapping("/download/{resumeId}")
	public void queryByResumeId(@PathVariable("resumeId") Long resumeId, HttpServletResponse response){
		HrResume hrResume = hrResumeService.selectHrResumeById(resumeId);
		// 假设RuoYiConfig和hrBgfile是已经定义好的类或者对象
		// 按照文件的路径进行拼接
		String baseDir = RuoYiConfig.getProfile(); // 获取基础目录
		String fileRelativePath = hrResume.getResumeUrl(); // 获取文件的相对路径，如 /profile/upload/2024/08/18/黄涛涛_20240818174831A001.pdf
		String filePath = baseDir + fileRelativePath.replaceFirst("/profile", ""); // 移除开头的"/profile"
		// 设置HTTP响应头，以便浏览器知道如何处理响应内容
		response.setContentType("application/pdf"); // 根据文件类型设置，这里是PDF文件
		response.setHeader("Content-Disposition", "attachment; filename=\"" + new File(filePath).getName() + "\""); // 设置文件下载名
		try (FileInputStream fis = new FileInputStream(filePath);
			 ServletOutputStream os = response.getOutputStream()) {
			byte[] buffer = new byte[1024];
			int bytesRead;
			while ((bytesRead = fis.read(buffer)) != -1) {
				os.write(buffer, 0, bytesRead); // 注意这里只写入实际读取的字节数
			}
			os.flush(); // 确保所有内容都被写入
		} catch (IOException e) {
			// 处理异常，例如记录日志或发送错误响应
			e.printStackTrace();
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 设置HTTP状态码为500
		}
	}
}
